package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.dongdongshop.constant.HttpResultEnum;
import com.dongdongshop.data.DataResult;
import com.dongdongshop.pojo.cart.Cart;
import com.dongdongshop.pojo.user.TbAddress;
import com.dongdongshop.pojo.user.TbUser;
import com.dongdongshop.service.cart.CartService;
import com.dongdongshop.service.order.OrderService;
import com.dongdongshop.service.user.AddressService;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

/**
 * 订单
 * @Author Eayon
 * @Date 2020/3/14 16:11
 */
@Controller
@RequestMapping("order")
public class OrderController {

    private static final Logger log = LoggerFactory.getLogger(OrderController.class);

    @Reference(check = false)
    private AddressService addressService;

    @Reference(check = false)
    private CartService cartService;

    @Reference(check = false)
    private OrderService orderService;

    @RequestMapping("toOrderInfo")
    public String toOrderInfo(@RequestParam("itemIds")Long[] itemIds, Model model){
        //获取当前登录的用户
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        //获取该用户的收货地址
        List<TbAddress> addressList = addressService.getAddressByUserId(user.getId());
        model.addAttribute("addressList",addressList);

        //调用购物车服务获取该用户选中购物车这几样商品的数据，（暂时不作删除，等生成订单的时候再做删除）
        //其实返回来的还是个购物车。只不过购物车里面都是用户结算时的商品
        List<Cart> carts = cartService.getItemsByItemId(itemIds,user.getUsername());
        model.addAttribute("carts",carts);
        return "order/getOrderInfo";
    }

    /**
     * 创建订单
     * @param id
     * @param carts
     */
    @RequestMapping("addOrder")
    @ResponseBody
    public DataResult addOrder(Long id,String carts){
        try {
            //获取登录用户
            TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
            //需要创建订单的购物车
            List<Cart> cartList = JSON.parseArray(carts, Cart.class);
            orderService.addOrder(cartList, id, user);//返回主订单id
        }catch (Exception e){
            log.error("创建订单异常",e);
            return new DataResult(HttpResultEnum.ERROR.getCode(),HttpResultEnum.ERROR.getMessage());
        }
        return new DataResult(HttpResultEnum.SUCCESS.getCode(),HttpResultEnum.SUCCESS.getMessage());
    }

    /**
     * 跳转支付页面
     * @return
     */
    @RequestMapping("toPay")
    public String toPay(){
        return "order/pay";
    }

}
